<template>
  <div class="user-avatar">
    <!-- 头像触发按钮 -->
    <div class="avatar-trigger" @click="toggleDropdown">
      <div
        class="avatar-container"
        :class="{ 'active': showDropdown }"
      >
        <!-- 用户头像 -->
        <img
          v-if="user?.avatar"
          :src="user.avatar"
          :alt="user.username || 'User'"
          class="avatar-image"
          @error="handleImageError"
        >
        
        <!-- 默认头像 -->
        <div
          v-else
          class="avatar-placeholder"
          :style="{ backgroundColor: avatarColor }"
        >
          {{ avatarInitials }}
        </div>
        
        <!-- 在线状态指示器 -->
        <div
          v-if="showStatus"
          class="status-indicator"
          :class="statusClass"
        ></div>
      </div>
    </div>
    
    <!-- 下拉菜单 -->
    <Transition name="dropdown">
      <div
        v-if="showDropdown"
        class="dropdown-menu"
        @click.stop
      >
        <!-- 用户信息 -->
        <div class="user-info">
          <div class="user-details">
            <h4 class="user-name">{{ user?.username || '未登录' }}</h4>
            <p class="user-email">{{ user?.email || '' }}</p>
          </div>
          
          <!-- 用户等级/角色 -->
          <div v-if="user?.role" class="user-badge">
            <span class="badge" :class="getRoleClass(user.role)">
              {{ getRoleText(user.role) }}
            </span>
          </div>
        </div>
        
        <!-- 菜单分隔线 -->
        <div class="menu-divider"></div>
        
        <!-- 菜单项 -->
        <div class="menu-items">
          <!-- 个人资料 -->
          <button
            @click="handleMenuClick('profile')"
            class="menu-item"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/>
              <circle cx="12" cy="7" r="4"/>
            </svg>
            <span>个人资料</span>
          </button>
          
          <!-- 账户设置 -->
          <button
            @click="handleMenuClick('settings')"
            class="menu-item"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <circle cx="12" cy="12" r="3"/>
              <path d="M12 1v6m0 6v6m11-7h-6m-6 0H1m17-4a4 4 0 0 1-8 0 4 4 0 0 1 8 0zM7 21a4 4 0 0 1-8 0 4 4 0 0 1 8 0z"/>
            </svg>
            <span>账户设置</span>
          </button>
          
          <!-- 我的任务 -->
          <button
            @click="handleMenuClick('tasks')"
            class="menu-item"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
              <polyline points="14,2 14,8 20,8"/>
              <line x1="16" y1="13" x2="8" y2="13"/>
              <line x1="16" y1="17" x2="8" y2="17"/>
              <polyline points="10,9 9,10 8,9"/>
            </svg>
            <span>我的任务</span>
            <span v-if="taskCount > 0" class="item-badge">{{ taskCount }}</span>
          </button>
          
          <!-- 使用统计 -->
          <button
            @click="handleMenuClick('statistics')"
            class="menu-item"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M3 3v18h18"/>
              <path d="M18.7 8l-5.1 5.2-2.8-2.7L7 14.3"/>
            </svg>
            <span>使用统计</span>
          </button>
          
          <!-- 帮助中心 -->
          <button
            @click="handleMenuClick('help')"
            class="menu-item"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <circle cx="12" cy="12" r="10"/>
              <path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/>
              <line x1="12" y1="17" x2="12.01" y2="17"/>
            </svg>
            <span>帮助中心</span>
          </button>
        </div>
        
        <!-- 菜单分隔线 -->
        <div class="menu-divider"></div>
        
        <!-- 底部操作 -->
        <div class="menu-actions">
          <!-- 主题切换 -->
          <button
            @click="toggleTheme"
            class="menu-item"
          >
            <svg v-if="isDarkMode" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <circle cx="12" cy="12" r="5"/>
              <line x1="12" y1="1" x2="12" y2="3"/>
              <line x1="12" y1="21" x2="12" y2="23"/>
              <line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/>
              <line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/>
              <line x1="1" y1="12" x2="3" y2="12"/>
              <line x1="21" y1="12" x2="23" y2="12"/>
              <line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/>
              <line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/>
            </svg>
            <svg v-else width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>
            </svg>
            <span>{{ isDarkMode ? '浅色模式' : '深色模式' }}</span>
          </button>
          
          <!-- 退出登录 -->
          <button
            @click="handleLogout"
            class="menu-item logout-item"
            :disabled="loggingOut"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/>
              <polyline points="16,17 21,12 16,7"/>
              <line x1="21" y1="12" x2="9" y2="12"/>
            </svg>
            <span>{{ loggingOut ? '退出中...' : '退出登录' }}</span>
          </button>
        </div>
      </div>
    </Transition>
    
    <!-- 遮罩层 -->
    <Transition name="dropdown-overlay">
      <div
        v-if="showDropdown"
        class="dropdown-overlay"
        @click="closeDropdown"
      ></div>
    </Transition>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useTaskStore } from '@/stores/task'
import { useSettingsStore } from '@/stores/settings'

interface User {
  id: string
  username: string
  email: string
  avatar?: string
  role: 'user' | 'admin' | 'premium'
  status?: 'online' | 'offline' | 'away'
}

interface Props {
  showStatus?: boolean
  size?: 'small' | 'medium' | 'large'
}

const props = withDefaults(defineProps<Props>(), {
  showStatus: true,
  size: 'medium'
})

// Stores
const router = useRouter()
const userStore = useUserStore()
const taskStore = useTaskStore()
const settingsStore = useSettingsStore()

// 响应式数据
const showDropdown = ref(false)
const loggingOut = ref(false)
const imageError = ref(false)

// 计算属性
const user = computed(() => userStore.currentUser)
const taskCount = computed(() => taskStore.activeTasks.length)
const isDarkMode = computed(() => settingsStore.theme === 'dark')

const avatarInitials = computed(() => {
  if (!user.value?.username) return '?'
  const name = user.value.username
  return name.length > 1 ? name.substring(0, 2).toUpperCase() : name.toUpperCase()
})

const avatarColor = computed(() => {
  if (!user.value?.username) return '#6b7280'
  
  // 根据用户名生成颜色
  const colors = [
    '#ef4444', '#f97316', '#f59e0b', '#eab308',
    '#84cc16', '#22c55e', '#10b981', '#14b8a6',
    '#06b6d4', '#0ea5e9', '#3b82f6', '#6366f1',
    '#8b5cf6', '#a855f7', '#d946ef', '#ec4899'
  ]
  
  let hash = 0
  for (let i = 0; i < user.value.username.length; i++) {
    hash = user.value.username.charCodeAt(i) + ((hash << 5) - hash)
  }
  
  return colors[Math.abs(hash) % colors.length]
})

const statusClass = computed(() => {
  const status = user.value?.status || 'offline'
  return {
    'status-online': status === 'online',
    'status-away': status === 'away',
    'status-offline': status === 'offline'
  }
})

// 方法
const toggleDropdown = () => {
  showDropdown.value = !showDropdown.value
}

const closeDropdown = () => {
  showDropdown.value = false
}

const handleImageError = () => {
  imageError.value = true
}

const handleMenuClick = (action: string) => {
  closeDropdown()
  
  switch (action) {
    case 'profile':
      router.push('/profile')
      break
    case 'settings':
      router.push('/settings')
      break
    case 'tasks':
      router.push('/tasks')
      break
    case 'statistics':
      router.push('/statistics')
      break
    case 'help':
      router.push('/help')
      break
  }
}

const toggleTheme = () => {
  const newTheme = isDarkMode.value ? 'light' : 'dark'
  settingsStore.updateSetting('theme', newTheme)
  closeDropdown()
}

const handleLogout = async () => {
  if (!confirm('确定要退出登录吗？')) return
  
  loggingOut.value = true
  
  try {
    await userStore.logout()
    router.push('/login')
  } catch (error) {
    console.error('Logout failed:', error)
  } finally {
    loggingOut.value = false
    closeDropdown()
  }
}

const getRoleClass = (role: string) => {
  const classes = {
    admin: 'badge-admin',
    premium: 'badge-premium',
    user: 'badge-user'
  }
  return classes[role as keyof typeof classes] || 'badge-user'
}

const getRoleText = (role: string) => {
  const texts = {
    admin: '管理员',
    premium: '高级用户',
    user: '普通用户'
  }
  return texts[role as keyof typeof texts] || '用户'
}

// 点击外部关闭下拉菜单
const handleClickOutside = (event: Event) => {
  const target = event.target as Element
  if (!target.closest('.user-avatar')) {
    closeDropdown()
  }
}

// 生命周期
onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
.user-avatar {
  position: relative;
}

.avatar-trigger {
  cursor: pointer;
}

.avatar-container {
  position: relative;
  display: inline-block;
  transition: all 0.2s ease;
}

.avatar-container:hover {
  transform: scale(1.05);
}

.avatar-container.active {
  transform: scale(1.05);
}

.avatar-image,
.avatar-placeholder {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  border: 2px solid #e5e7eb;
  transition: all 0.2s ease;
}

.avatar-image {
  object-fit: cover;
}

.avatar-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: 600;
  color: white;
}

.avatar-container:hover .avatar-image,
.avatar-container:hover .avatar-placeholder {
  border-color: #3b82f6;
}

.status-indicator {
  position: absolute;
  bottom: 2px;
  right: 2px;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  border: 2px solid white;
}

.status-online {
  background: #10b981;
}

.status-away {
  background: #f59e0b;
}

.status-offline {
  background: #6b7280;
}

/* 下拉菜单 */
.dropdown-menu {
  position: absolute;
  top: 100%;
  right: 0;
  width: 280px;
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  margin-top: 8px;
  overflow: hidden;
}

.dropdown-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
}

/* 用户信息 */
.user-info {
  padding: 16px 20px;
  background: #f9fafb;
}

.user-details {
  margin-bottom: 8px;
}

.user-name {
  font-size: 16px;
  font-weight: 600;
  color: #111827;
  margin: 0 0 2px 0;
}

.user-email {
  font-size: 13px;
  color: #6b7280;
  margin: 0;
}

.user-badge {
  display: flex;
  justify-content: flex-start;
}

.badge {
  padding: 2px 8px;
  font-size: 11px;
  font-weight: 500;
  border-radius: 12px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.badge-admin {
  background: #fef3c7;
  color: #92400e;
}

.badge-premium {
  background: #e0e7ff;
  color: #3730a3;
}

.badge-user {
  background: #f3f4f6;
  color: #374151;
}

/* 菜单分隔线 */
.menu-divider {
  height: 1px;
  background: #e5e7eb;
  margin: 0;
}

/* 菜单项 */
.menu-items,
.menu-actions {
  padding: 8px 0;
}

.menu-item {
  display: flex;
  align-items: center;
  gap: 12px;
  width: 100%;
  padding: 10px 20px;
  font-size: 14px;
  color: #374151;
  background: transparent;
  border: none;
  cursor: pointer;
  transition: all 0.2s ease;
  text-align: left;
}

.menu-item:hover {
  background: #f3f4f6;
  color: #111827;
}

.menu-item:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.menu-item svg {
  flex-shrink: 0;
  color: #6b7280;
}

.menu-item:hover svg {
  color: #374151;
}

.logout-item {
  color: #dc2626;
}

.logout-item:hover {
  background: #fef2f2;
  color: #b91c1c;
}

.logout-item svg {
  color: #dc2626;
}

.logout-item:hover svg {
  color: #b91c1c;
}

.item-badge {
  margin-left: auto;
  padding: 2px 6px;
  font-size: 11px;
  font-weight: 600;
  background: #3b82f6;
  color: white;
  border-radius: 10px;
  min-width: 18px;
  text-align: center;
}

/* 尺寸变体 */
.user-avatar.small .avatar-image,
.user-avatar.small .avatar-placeholder {
  width: 32px;
  height: 32px;
}

.user-avatar.small .avatar-placeholder {
  font-size: 12px;
}

.user-avatar.large .avatar-image,
.user-avatar.large .avatar-placeholder {
  width: 48px;
  height: 48px;
}

.user-avatar.large .avatar-placeholder {
  font-size: 16px;
}

/* 动画 */
.dropdown-enter-active,
.dropdown-leave-active {
  transition: all 0.3s ease;
}

.dropdown-enter-from {
  opacity: 0;
  transform: translateY(-10px) scale(0.95);
}

.dropdown-leave-to {
  opacity: 0;
  transform: translateY(-10px) scale(0.95);
}

.dropdown-overlay-enter-active,
.dropdown-overlay-leave-active {
  transition: opacity 0.3s ease;
}

.dropdown-overlay-enter-from,
.dropdown-overlay-leave-to {
  opacity: 0;
}

/* 响应式设计 */
@media (max-width: 640px) {
  .dropdown-menu {
    width: 260px;
  }
  
  .user-info {
    padding: 12px 16px;
  }
  
  .menu-item {
    padding: 8px 16px;
  }
}

/* 深色主题 */
@media (prefers-color-scheme: dark) {
  .dropdown-menu {
    background: #1f2937;
    border-color: #374151;
  }
  
  .user-info {
    background: #111827;
  }
  
  .user-name {
    color: #f9fafb;
  }
  
  .user-email {
    color: #9ca3af;
  }
  
  .menu-divider {
    background: #374151;
  }
  
  .menu-item {
    color: #e5e7eb;
  }
  
  .menu-item:hover {
    background: #374151;
    color: #f9fafb;
  }
  
  .menu-item svg {
    color: #9ca3af;
  }
  
  .menu-item:hover svg {
    color: #e5e7eb;
  }
  
  .logout-item:hover {
    background: #7f1d1d;
  }
}
</style>